package com.yifi.common.plugins.shiro;

import com.yifi.system.domain.MisUser;
import com.yifi.system.service.MisUserService;
import com.yifi.system.service.UserLimitService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Set;

/**
 * @author 姚善利
 * @classname com.yifi.common.shrio
 * @description
 * @date 2022/12/15 10:57
 */
public class UserRealm extends AuthorizingRealm {

    private static final Logger log = LoggerFactory.getLogger(UserRealm.class);

    UserLimitService userLimitService=new UserLimitService();
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        MisUser misUser = (MisUser) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //stringPermissions结构：
        //user
        //user:list
        //user:add
        //user:edit
        //...
        // 管理员拥有所有权限
        if (misUser.getCcode().equals("admin"))
        {
            info.addRole("admin");
            info.addStringPermission("*:*:*");
        }
        else
        {
            Set<String> roles = userLimitService.getRoles(misUser.getCcode());
            info.setRoles(roles);
            //根据用户获取权限
            Set<String> stringPermissions = userLimitService.getPermissions(misUser.getCcode());
            info.setStringPermissions(stringPermissions);
        }
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
        String username = upToken.getUsername();
        String password = "";
        if (upToken.getPassword() != null)
        {
            password = new String(upToken.getPassword());
        }

        MisUserService misUserService=new MisUserService();
        MisUser user = null;
        try
        {
            user = misUserService.getMisUser(username, password);
        }
        catch (Exception e)
        {
            log.info("对用户[" + username + "]进行登录验证..验证未通过{}", e.getMessage());
            throw new AuthenticationException(e.getMessage(), e);
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
        return info;
    }
}
